package pers.qianyu.month_202012.date_20201209;

import java.util.*;

/**
 * [同date_20201113]
 * 752. 打开转盘锁
 * https://leetcode-cn.com/problems/open-the-lock/
 *
 * @author mizzle rain
 * @date 2020-12-09 15:52
 */
public class OpenLock {
    public int openLock(String[] deadends, String target) {
        Queue<String> q = new LinkedList<>();
        Set<String> visited = new HashSet<>();
        int step = 0;
        q.add("0000");
        visited.add("0000");
        while (!q.isEmpty()) {
            int size = q.size();
            for (int i = 0; i < size; i++) {
                String str = q.poll();
                if (contains(deadends, str)) {
                    continue;
                }
                if (str.equals(target)) {
                    return step;
                }
                for (int k = 0; k < 4; k++) {
                    String a = add(str, k, 1);
                    if (!visited.contains(a)) {
                        q.offer(a);
                        visited.add(a);
                    }
                    String b = add(str, k, -1);
                    if (!visited.contains(b)) {
                        q.offer(b);
                        visited.add(b);
                    }
                }
            }
            step++;
        }
        return -1;
    }

    private boolean contains(String[] deadends, String s) {
        for (String d : deadends) {
            if (d.equals(s)) {
                return true;
            }
        }
        return false;
    }

    private String add(String str, int index, int num) {
        char[] arr = str.toCharArray();
        int i = arr[index] + num;
        if (i > '9') {
            arr[index] = '0';
        } else if (i < '0') {
            arr[index] = '9';
        } else {
            arr[index] = (char) i;
        }
        return new String(arr);
    }
}
